package com.alingrad.android.froyoengine.graphics;

import com.alingrad.android.froyoengine.AllocationGuard;
import com.alingrad.android.froyoengine.GameRenderer;
import com.alingrad.android.froyoengine.util.FixedSizeArray;
import com.alingrad.android.froyoengine.util.GLColor;

public class RenderManager extends AllocationGuard {
	private FixedSizeArray<FixedSizeArray<RenderNode>> mRenderLists;
	private RenderNodePool mNodePool;
	private final GameRenderer mRenderer;
	private int mRenderListIndex;

	public RenderManager(final GameRenderer renderer) {
		super();
		mRenderer = renderer;
		mRenderListIndex = 0;
		mRenderLists = new FixedSizeArray<FixedSizeArray<RenderNode>>(2);
		mNodePool = new RenderNodePool(GameRenderer.MAX_RENDER_NODES * 2);
		for (int i = 0; i < 2; i++)
			mRenderLists.add(new FixedSizeArray<RenderNode>(GameRenderer.MAX_RENDER_NODES));
	}

//	public void scheduleToRender(final Renderable object) {
//		scheduleToRender(object, 0f, 0f, 0f, 0f, 1f, 1f);
//	}

	public void scheduleToRender(final Renderable object, final float x, final float y, final float z, final float rotation) {
		scheduleToRender(object, x, y, z, rotation, 1f, 1f);
	}

	public void scheduleToRender(final Renderable object, final float x, final float y, final float z, final float rotation, final float scaleX, final float scaleY) {
		RenderNode node = mNodePool.allocate(object, x, y, z, scaleX, scaleY, rotation);
		mRenderLists.get(mRenderListIndex).add(node);
	}

	public void sync() {
		mRenderer.updateList(mRenderLists.get(mRenderListIndex));

		mRenderListIndex = (mRenderListIndex + 1) % 2;
		emptyList(mRenderLists.get(mRenderListIndex));
	}

	private void emptyList(FixedSizeArray<RenderNode> list) {
		while (!list.isEmpty())
			mNodePool.release(list.removeLast());
	}

	public void setBackgroundColor(GLColor color) {
		mRenderer.setBackgroundColor(color);
	}
}
